package com.example.yian.controller;

import com.example.yian.entity.*;
import com.example.yian.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
public class SecurityRiskController {

    private static final Logger log = LoggerFactory.getLogger(SecurityRiskController.class);
    @Autowired
    private SecurityRiskService securityRiskService;

    @Autowired
    private RiskRectificationService riskRectificationService;

    @Autowired
    private WeChatAuthService weChatAuthService;

    @Autowired
    private SecurityRiskReportService reportService;

    @Autowired
    private TextSearchService textSearchService;

    @PostMapping("/addSecurityRisks")
    public Map<String, Object> handleAddSecurityRisk(@RequestHeader("Authorization") String token, @RequestBody Map<String, String> requestBody) {
        Map<String, Object> response = new HashMap<>();
        Optional<Long> userIdOpt = weChatAuthService.getUserIdFromToken(token);

        log.info("addSecurityRisks: requestBody:{}", requestBody);

        log.info("addSecurityRisks | Step1");
        if (userIdOpt.isPresent()) {
            Long userId = userIdOpt.get();
            String image = requestBody.get("image");

            String chatId = (String)requestBody.get("chatId");
            if(chatId == null)
            {
                chatId = "5261ef24-1cf8-11ef-bbae-0242ac110002";
            }

            String textId = (String)requestBody.get("textId");
            //String supplementContents = requestBody.get("supplement_contents");
            String supplementContents = "";
            SecurityRisk securityRisk = securityRiskService.addSecurityRisk(image, chatId, textId, supplementContents, userId);

            //同步保存Response到数据库
            log.info("addSecurityRisks | Step2");
            {
                String savetextId = Optional.ofNullable(requestBody.get("textId")).map(Object::toString).orElse("");
                 String content = Optional.ofNullable(requestBody.get("saveSearchText")).map(Object::toString).orElse("");
                String refText = Optional.ofNullable(requestBody.get("refText")).map(Object::toString).orElse("");
                String requestIdStr = Optional.ofNullable(requestBody.get("requestId")).map(Object::toString).orElse("");
                String saveChatId = Optional.ofNullable(requestBody.get("chatId")).map(Object::toString).orElse("");
                log.error("addSecurityRisks | request_id:{},saveTextId:{},refText:{},saveChatId:{},{}",requestIdStr,savetextId,refText,saveChatId,content);
                Long lRequestId = null;
                if (requestIdStr != null) {
                    try {
                        lRequestId = Long.parseLong(requestIdStr);
                    } catch (NumberFormatException e) {
                        // 处理转换异常
                        System.out.println("转换错误: " + e.getMessage());
                    }
                }
                else {
                    log.info("RequestId is null");
                }
                //requestId =  textSearchService.getCurRequstId();
                //isEnd标志
                Boolean isEnd = null;
                String isEndStr = (String) requestBody.get("isEnd");
                if(isEndStr == null)
                {
                    isEnd = true;
                }
                else
                {
                    switch (isEndStr.toLowerCase()) {
                        case "true":
                            isEnd = true;
                            break;
                        case "false":
                            isEnd = false;
                            break;
                        default:
                            log.info("parse isEnd false");
                            isEnd = false;  // 默认为 false
                    }
                }
                String operateStr = (String) requestBody.get("operate");
                Boolean operate = null;
                if(operateStr == null)
                {
                    operate = true;
                }
                else {
                    switch (operateStr.toLowerCase()) {
                        case "true":
                            operate = true;
                            break;
                        case "false":
                            operate = false;
                            break;
                        default:
                            log.info(" parse operate false");
                            operate = false;  // 默认为 false
                    }
                }


                String saveUserId = userIdOpt.get().toString();//(String) requestBody.get("userId");
                Optional<TextSearchResponse> ResponseOpt = textSearchService.findByTextId(textId);
                if(ResponseOpt.isPresent())
                {
                    log.error("saveSearchText | textResponseOpt is present,textId:{}，content:{},requstId:{}，userId:{}",textId,"",lRequestId,saveUserId);
                    response.put("code", 500);
                    response.put("msg", "重复条目存在");
                    response.put("time", Instant.now().toEpochMilli());
                    response.put("data", new HashMap<>());
                }
                else {

                    log.error("addSecurityRisks | saveSearchText | enter function,textId:{ },{}",textId,content);
                    textSearchService.InsertTextSearchResponse(lRequestId, saveChatId, textId, operate, content, refText, isEnd);

                    response.put("code", 200);
                    response.put("msg", "成功");
                    response.put("data", Map.of("risks_id", securityRisk.GetId()));
                }
            }

            log.info("addSecurityRisks | Step3");
            response.put("code", 200);
            response.put("msg", "成功");
            response.put("data", Map.of("risks_id", securityRisk.GetId()));
        } else {
            response.put("code", 401);
            response.put("msg", "未授权");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
        }
        return response;
    }

    @GetMapping("/getSecurityRisks")
    public Map<String, Object> getSecurityRiskWithDetails(@RequestParam Long risksId) {
        Map<String, Object> response = new HashMap<>();
        Optional<SecurityRisk> riskOpt = securityRiskService.getSecurityRiskWithDetails(risksId);

        if (riskOpt.isPresent()) {
            Optional<TextSearchResponse> responseOpt = textSearchService.findByTextId(riskOpt.get().getTextId());
            if(responseOpt.isPresent()) {
                Optional<TextSearchRequest> requestOpt = textSearchService.findRequestById(responseOpt.get().getRequestId());
                String searchText = requestOpt.get().getTextMessage();
                response.put("data", securityRiskService.addSearchTextToRisk(riskOpt.get(), searchText));
            }
            else
            {
                response.put("data", securityRiskService.addSearchTextToRisk(riskOpt.get(), ""));
            }

            //获取对应的整改信息
            Optional<RiskRectification> rectificationOpt = Optional.ofNullable(riskRectificationService.getRectificationByRiskId(risksId));
            if(rectificationOpt.isPresent())
            {
              /*  response.put("rectificationImage", rectificationOpt.get().getImage());

                Timestamp createdAt = rectificationOpt.get().GetCreatedAt();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedDate = sdf.format(createdAt);
                response.put("rectificationCompleteTime", formattedDate);
                response.put("isRectification", true);*/
                Map<String, String> data = (Map<String, String>) response.get("data");

                data.put("rectificationImage", rectificationOpt.get().getImage());

                Timestamp createdAt = rectificationOpt.get().GetCreatedAt();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedDate = sdf.format(createdAt);
                data.put("rectificationCompleteTime", formattedDate);

                data.put("isRectification", "1");
            }
            else
            {
             /*   response.put("rectificationImage", "");
                response.put("rectificationCompleteTime", "");
                response.put("isRectification", false);*/
                Map<String, String> data = (Map<String, String>) response.get("data");

                data.put("rectificationImage", "");
                data.put("rectificationCompleteTime", "");
                data.put("isRectification", "2");
            }

            response.put("code", 200);
            response.put("msg", "成功");
            //   response.put("data", riskOpt.get());
        } else {
            response.put("code", 404);
            response.put("msg", "未找到记录");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
        }
        return response;
    }

    /**
     * 分页获取指定用户的隐患列表
     * @param requestParams 请求参数，包含分页信息及用户ID
     * @param token 访问令牌
     * @return 分页数据及状态信息
     */
    @PostMapping("/getRiskLists")
    public Map<String, Object> getRiskLists(
            @RequestBody Map<String, Object> requestParams,
            @RequestHeader("Authorization") String token) {
        Map<String, Object> response = new LinkedHashMap<>();
        Optional<Long> userIdOpt = weChatAuthService.getUserIdFromToken(token);

        if (!userIdOpt.isPresent()) {
            response.put("code", 401);
            response.put("msg", "未授权");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
            return response;
        }
        Long userId = userIdOpt.get();
        // 从请求体中提取分页参数
        Integer pageNum = (Integer) requestParams.getOrDefault("page", 1);
        Integer pageSize = (Integer) requestParams.getOrDefault("size", 1000);
        String  startTime = (String) requestParams.getOrDefault("startTime", "2024-03-03");
        if (Objects.equals(startTime, "")) {
            startTime = (String) "2024-03-03";
        }
        String endTime = (String) requestParams.getOrDefault("endTime", "2099-08-15");
        if (Objects.equals(endTime, "")) {
            endTime = (String) "2099-08-15";
        }

        //获取过滤标志
        int isSpecificationSearch = (Integer) requestParams.getOrDefault("isRectification", 0);

        Page<SecurityRisk> page = new Page<>(pageNum, pageSize);
        IPage<SecurityRisk> riskPage = securityRiskService.getRiskListsByUserId(userId, pageNum, pageSize, startTime,endTime, isSpecificationSearch);
        response.put("code", 200);
        response.put("msg", "成功");
        response.put("time", Instant.now().toEpochMilli());
        response.put("total", riskPage.getTotal());

        //重新拿取一把
        List<SecurityRisk> risks = riskPage.getRecords();

        if(risks.size() == 0)
        {
            log.error("getRiskLists | risks is empty");
        }
        List<Map<String, Object>> dataWithExtraFields = new ArrayList<>();
        for (SecurityRisk risk : risks) {
            Map<String, Object> dataItem = new HashMap<>();
            dataItem.put("id", risk.GetId()); // 假设 id 是一个 Long 类型的字段
            dataItem.put("userId", risk.GetUserId()); // 假设 otherField 是另一个 Long 类型的字段
            dataItem.put("image", risk.getImage());
            dataItem.put("chatId", risk.GetChatId());
            dataItem.put("textId", risk.getTextId());
            Optional<TextSearchResponse> responseOpt = textSearchService.findByTextId(risk.getTextId());
            if(responseOpt.isPresent()) {
                Optional<TextSearchRequest> requestOpt = textSearchService.findRequestById(responseOpt.get().getRequestId());
                String searchText = requestOpt.get().getTextMessage();
                dataItem.put("searchText", searchText);
            }
            else
            {
                dataItem.put("searchText", "");
            }

            //检查是否有对应的整改信息
            boolean isRectificationed = false;
            Optional<RiskRectification> rectificationOpt = Optional.ofNullable(riskRectificationService.getRectificationByRiskId(risk.GetId()));
            if(rectificationOpt.isPresent())
            {
                dataItem.put("isRectification", "1");
                isRectificationed = true;
            }
            else {
                dataItem.put("isRectification", "2");
                isRectificationed = false;
            }

            dataItem.put("supplementContents", risk.GetSupplementContents());
            dataItem.put("createdAt", risk.GetCreatedAt());
            dataItem.put("updatedAt", risk.GetUpdatedAt());
            //根据条件过滤
            if (isSpecificationSearch == 0 ||
                    (isSpecificationSearch == 1 && isRectificationed) ||
                    (isSpecificationSearch == 2 && !isRectificationed)) {
                dataWithExtraFields.add(dataItem);
            }

        }
        response.put("data",dataWithExtraFields);

        return response;
    }


    @PostMapping("/weeklyRiskCounts")
    public ResponseEntity<Map<String, Object>> getWeeklyRiskCounts(
            @RequestHeader("Authorization") String token) {
        Map<String, Object> response = new LinkedHashMap<>();
        Optional<Long> userIdOpt = weChatAuthService.getUserIdFromToken(token);

        if (!userIdOpt.isPresent()) {
            response.put("code", 401);
            response.put("msg", "未授权");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
            // return  ResponseEntity.ok(response);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
        Long userId = userIdOpt.get();
        Map<LocalDate, Long> countsByDay = securityRiskService.countRisksByDayOfWeekForUser(userId);
        // 将LocalDate转换为字符串，便于前端处理（可选，取决于前端需求）
        Map<String, Long> formattedCounts = new HashMap<>();
        countsByDay.forEach((date, count) -> formattedCounts.put(date.toString(), count));
        response.put("code", 200);
        response.put("msg", "成功");
        response.put("data", formattedCounts);
        return ResponseEntity.ok(response);
    }


    @PostMapping("/addRectification")
    public Map<String, Object> handleAddRectification(@RequestHeader("Authorization") String token, @RequestBody Map<String, String> requestBody) {
        Map<String, Object> response = new HashMap<>();
        Optional<Long> userIdOpt = weChatAuthService.getUserIdFromToken(token);

        if (userIdOpt.isEmpty()) {
            log.error("addRectification | cannot find userId by AuthCode!");
            response.put("code", 401);
            response.put("msg", "登录过期");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
            return response;
        }

        Long riskId = Long.valueOf(requestBody.get("riskId"));
        String strRectificationContent = requestBody.get("rectificationContent");
        if (strRectificationContent == null || strRectificationContent.trim().isEmpty()) {
            strRectificationContent = "";
        }
        String strImage = requestBody.get("image");

        RiskRectification riskRectification = riskRectificationService.addRiskRectification(riskId, strImage, strRectificationContent);

        if (riskRectification == null) {
            log.error("addRecification failed!");
            response.put("code", 500);
            response.put("msg", "添加失败");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
        } else {
            log.info("addRecification success!");
            response.put("code", 200);
            response.put("msg", "成功");
            response.put("data", Map.of("rectificationId", String.valueOf(riskRectification.getId())));
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedNow = now.format(formatter);
            response.put("rectificationCompleteTime", formattedNow);
        }
        return response;
    }

}
